<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Controller;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class EnsureTokenIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $data = $request->json()->all();

        if(!isset($data['token']) || $data['token'] == ''){
            return response()->json([
                'code' => 203,
                'msg' => '请先登录',
                'data'=> new \stdClass()
            ]);
        }
        $user_info = DB::table('users')->where('token',$data['token'])->first();
        if(empty($user_info)){
            return response()->json([
                'code' => 203,
                'msg' => '请先登录',
                'data'=> new \stdClass()
            ]);
        }

        $request->merge(['user_id' => $user_info->id]);

        return $next($request);
    }
}
